<?php
/**
 * 文件上传类
 * @param
 * @author Mr.Liu
 * @Time: 15:16
 */

namespace App\Services;

use App\Models\ActivitySale;
use App\Models\ActivityType;
use App\Models\User;
use App\Models\UserReward;
use Illuminate\Filesystem\Cache;
use Illuminate\Support\Facades\DB;

class IssueService
{
    protected $activity;
    protected $activity_type;

    const  SuccessStatus = 1;
    const  FailStatus = 0;

    public function __construct()
    {

    }

    public function marketing($id)
    {
        $user = User::find($id);
        $this->activity_type = ActivityType::Where([['status', '1'],['start_at','<=',date('Y-m-d')],['end_at','>=',date('Y-m-d')]])->first();
        if ($this->activity_type && $user->id){
        $activity = ActivitySale::Where([['status', '1'], ['activity_type_id', $this->activity_type->id]])->get();
        if (!is_null($activity)) {
            try {
                DB::beginTransaction();
                foreach ($activity as $item => $value) {
                    $data[$item]['user_id'] = $user->id;
                    $data[$item]['activity_sale_id'] = $value->id;
                    $data[$item]['activity_type_id'] = $this->activity_type->id;
                    $data[$item]['card_name'] = $value->activity_name;
                    $data[$item]['type_source'] = 2;
                    $data[$item]['full'] = $value->full??0;
                    $data[$item]['money'] = $value->less??0;
                    if ($value->activity_time !== 0) {
                        $data[$item]['time_end_valid'] = strtotime(date('Y-m-d')) + 3600*24*($value->activity_time-1);
                    } else {
                        $data[$item]['time_end_valid'] = 0;
                    }
                    $data[$item]['time_start_valid'] = strtotime(date('Y-m-d'));
                    $data[$item]['created_at'] = date('Y-m-d h:m:s');
                    $value->amount += 1;
                    $value->save();
                }
                UserReward::insert($data);
                DB::commit();
                w_log('新人优惠礼包脚本执行成功：【' . json_encode(['uid'=>$user->id,'activity_type_id'=>$this->activity_type->id]) . '】' ,'issue');

                Cache::store('redis')->forget('user:info_' . $user->id);
                return true;
            } catch (\Exception $e) {
                DB::rollBack();
                $redis = app('redis.connection');
                w_log('新人优惠礼包脚本执行失败：【' . json_encode(['uid'=>$user->id,'activity_type_id'=>$this->activity_type->id]). $e->getMessage() . '】' ,'issue');
                $redisList = $redis->lpush('issue', json_encode(['uid'=>$user->id,'activity_type_id'=>$this->activity_type->id]));
                return false;
            }
        }
        }

    }
}